<?php
namespace app\api\controller;

use app\common\model\StateChange;
use think\Controller;
use think\Db;
use app\index\model\Zaixian;
use app\index\model\Username;
use app\index\model\RizhiJl;
header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");
class Login extends Controller
{
	private $user;

	public function _initialize(){

		parent::_initialize();
		//接收用户cookie信息
		if (isset($_COOKIE['appAndroid']) || isset($_COOKIE['appIOS'])) {
			$appinfo = isset($_COOKIE['appAndroid']) ? $_COOKIE['appAndroid'] : $_COOKIE['appIOS'];
			$cookieinfo = explode(',', $appinfo);
			cookie('username', trim($cookieinfo[0]));
			cookie('password', trim($cookieinfo[1]));
			cookie('login_key', trim($cookieinfo[3]));
			cookie('login_from', intval($cookieinfo[4]));
			if (isset($_COOKIE['appAndroid'])) {
				cookie('app_from', 1);
			} else {
				cookie('app_from', 2);
			}
		}
		$appfrom = cookie('app_from') ? cookie('app_from') : 0;
		$this->assign('appfrom', $appfrom);

		$map = array(
				'username' => input('username', ''),
				'login_key' => input('login_key', ''),
		);
		$this->user = Db::name('username')->where($map)->where('open', '<', 1)->find();
//验证加密
		$action = request()->action();
		if( 'agreement'!=$action && 'updateImg'!=$action ){
			$VALUE_KEY = ['afewfewfew21342dsaewf'=>'8f4da4f9ew4f98ewq65fwe48f9w'];
			$HEADER_TIME = isset($_SERVER['HTTP_TIME']) ? $_SERVER['HTTP_TIME'] : '';
			$HEADER_KEY = isset($_SERVER['HTTP_KEY']) ? $_SERVER['HTTP_KEY'] : '';
			$HEADER_SIGN = isset($_SERVER['HTTP_SIGN']) ? $_SERVER['HTTP_SIGN'] : '';

			$POST_LOGIN_KEY = isset($_SERVER['HTTP_LOGINKEY']) ? $_SERVER['HTTP_LOGINKEY'] : ( isset($_POST['login_key']) ? $_POST['login_key'] : '' );
			$POST_NAME = isset($_SERVER['HTTP_USERNAME']) ? $_SERVER['HTTP_USERNAME'] : (isset($_POST['username']) ? $_POST['username'] : (isset($_POST['name']) ? $_POST['name']:''));


			if( !isset($VALUE_KEY[$HEADER_KEY]) ){
				exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
			}

			$validation =  $HEADER_TIME.$VALUE_KEY[$HEADER_KEY].$POST_LOGIN_KEY.$POST_NAME;
			if( $HEADER_SIGN != md5($validation) ){
				exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
			}
		}
	}

	public function login(){
		header ( "Content-type: text/html; charset=utf-8" );
		$username = input('post.username');
		$password = input('post.password');
		$from = input('post.from',3);
		$where = array('BINARY username'=>$username,'password'=>$password);
		$data = Db::name('username')->where($where)->find();
		if($data){
			if($data['open']==1){
				$row = array(
						'result'=>0,
						'ResultMsg'=>'账号已冻结'
				);
				echo json_encode($row,JSON_UNESCAPED_UNICODE);
			}
			if($data['open']==0){
				$login_key = suiji_zifu(15);
				$login_time = time();
				$login_ip = get_ip();

				$zx_list = Db::name('zaixian')->where('username',$username)->find();
				$login_url = $_SERVER['HTTP_HOST'];
				$zaixian = new Zaixian();

				if($zx_list['id']){
					//更新在线
					$zaixian->updateOnlineTime($zx_list['id'],$username,$login_time,0,$login_ip,$login_url);
				}else{
					//插入在线
					$zaixian->setOnlineTime($username,$login_time,0,$login_ip,$login_url);
				}
				//会员等级提升
				//$us_class = Db::name('us_class')->field('id,czl,xml')->select();
				$usclass = $data['us_class'];
				/* foreach ($us_class as $v) {
					if($v['czl'] <= $data['czzje']) {
						if($v['xml'] <= $data['tzzje']) {
							$usclass = $v['id'];
						}
					}
				} */
				//更新用户登录时间
				$user = new Username();
				$user->updateLoginInfo($data['id'],$login_key,$login_time,$usclass,$login_ip);
				Db::name('username')->where('username',$username)->setInc('login_num');
				//日志记录
				$rizi = new RizhiJl();
				$rizi->setLog('2',admin_text(49),$login_time,$login_ip,$username,$from);

				//更新代理下线人数
				$user = Db::name('username')->where(['nbzh'=>0,'swzh'=>0,'open'=>0])->select();
				foreach ($user as $val){
					$user_dl = Db::name('username')->where('tjr',$val['username'])->where('tjrid',$val['id'])->count();
					$date['xjrens'] = $user_dl;
					Db::name('username')->where('id',$val['id'])->update($date);
				}
				$row = array(
						'result'=>1,
						'ResultMsg'=>'登录成功',
						'datas'=>array(
								'uid' => $data['id'],
								'username'=>$username,
								'password'=> $data['password'],
								'login_key'=>$login_key,
								'dl' => intval($data['dl']),
								'je'=>floatval($data['je']),
								'bank' => empty($data['bankno']) ? 0 : 1,
								'sw' => 0==intval($data['swzh']) ? 1:0,
								'image' => empty($data['img']) ? '' : $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/uploads/avatar/'.$data['img']
						)
				);
				echo json_encode($row,JSON_UNESCAPED_UNICODE);
			}
		}else{
			$row = array(
					'result'=>0,
					'ResultMsg'=>'账号密码不正确',
			);
			echo json_encode($row,JSON_UNESCAPED_UNICODE);
		}
	}
	public function checkLogin(){
		$row = array(
				'result'=>1,
				'ResultMsg'=>'',
		);
		$login_key = input('post.login_key');
		$name = input('post.name');
		$from = input('post.from',0);
		$map = array(
				'BINARY username' => $name,
				'login_key'  => $login_key
		);
		$user_all = Db::name('username')->where($map)->where('open','<',1)->find();
		if( empty($user_all) ){
			$row['datas'] = 1;
		}else{
			$post = input('post.');
			if( isset($post['RegistrationID']) && !empty($post['RegistrationID']) ){
				$r_id = trim($post['RegistrationID']);
				Db::name("username")->where(['registration_id'=>$r_id])->update(['registration_id'=>'']);
				Db::name("username")->where(['username'=>$name])->update(['registration_id'=>$r_id]);
			}

			if( 0==intval($user_all['current_from']) || time()-intval($user_all['diff_time']) > 300 ){
				Db::name("username")->where(['username'=>$name])->update(['current_from'=>$from,'current_time'=>time(),'diff_time'=>time()]);
			}
			Db::name("username")->where(['username'=>$name])->update(['diff_time'=>time()]);

			$row['datas'] = 0;
		}
		echo json_encode($row,JSON_UNESCAPED_UNICODE);
	}
	public function changePassword(){

		$row = array('result'=>1,'ResultMsg'=>'',);
		$user = $this->user;
		if(empty($user)){
			$ret['datas'] = 3; //用户未登录
			return json_encode($ret, JSON_UNESCAPED_UNICODE);
		}
		$post = input('post.');
		$name = $post['username'];
		$old_password = $post['old'];
		$new_password = $post['new'];
		//0：登录密码；1：提款密码
		$type = intval($post['type']);
		$password = 'password';
		$password_model = 'updatePass';
		if( 1==$type ){
			$password = 'ejmm';
			$password_model = 'updatePassEjmm';
		}
		$user_find = Db::name('username')->where(['username'=>$name])->field($password)->find();
		if($old_password != $new_password){
			if($old_password == $user_find[$password]){
				$ps = new Username();
				if($ps->$password_model($name, $new_password)){
					$row['datas'] = 1; //修改成功
				}else{
					$row['datas'] = 0; //修改失败
				}
			}else{
				$row['datas'] = 2; //前后密码不一致
			}
		}else{
			$row['datas'] = 3;
		}
		echo json_encode($row,JSON_UNESCAPED_UNICODE);
	}


	public function register(){

		$user_model = new Username();
		$reg_user = input('post.reg_user') ? input('post.reg_user') : '';
		$reg_pass = input('post.reg_pass') ? input('post.reg_pass') : '';
		$phone = input('post.reg_phone') ? input('post.reg_phone') : '';
		$reg_recommend = input('post.reg_recommend') ? input('post.reg_recommend') : '';
//		$verify_code = input('post.verify_code') ? input('post.verify_code') : '';
		$from = input('post.from',3);
		$row = array('result'=>1,'ResultMsg'=>'','status'=>1);
		if($reg_user && $reg_pass) {
			$reg_user = strtolower($reg_user);
			//验证用户名密码
			if(!checkNameInfo($reg_user)) {
				$row['status'] = 3;  //用户名（长度为6~16的字母或数字）
				return json_encode($row,JSON_UNESCAPED_UNICODE);
			}
			/*if(!checkPassInfo($reg_pass)) {
				$row['status'] = 4;  //密码（字母卡头,只包含数字字母下划线）
				return json_encode($row,JSON_UNESCAPED_UNICODE);
			}*/
			//判断是否需要验证验证码
//			$codeif = Db::name('xt_reg')->find();
//			if($codeif['codo_open'] == 1) {
//				if(!$verify_code || !captcha_check($verify_code)) {
//					$row['datas'] = 6;  //验证码无效
//					return json_encode($row,JSON_UNESCAPED_UNICODE);
//				}
//			}
			//验证用户手机号
			if( $phone && !checkPhone($phone)) {
				$row['status'] = 7;  //无效的手机号
				return json_encode($row,JSON_UNESCAPED_UNICODE);
			}
			$arr = array('id'=>0,'username'=>'','recommend'=>['0'=>'','1'=>0]);
			//判断推荐码是否有效
			if($reg_recommend) {
				$dl = Db::name('username')->field('username,tjm,id')->where(['swzh'=>0])->select();
				foreach ($dl as $val){
					if($val['tjm']==$reg_recommend){
						$data['dl']=1;
						$data['dl_time'] = time();
						$data['tjm']=$this->code();
						$arr['recommend'][0]=$val['tjm'];
						$arr['username'] = $val['username'];
						$arr['id']=$val['id'];
						 /*$val['tjm'] = explode('|', $val['tjm']);
						foreach ($val['tjm'] as $value){
							if(strpos($value, $reg_recommend)!==false){
								if(strpos($value,'-')!==false){
									$arr['recommend'] = explode('-',$value);
								}else{
									$arr['recommend'][0]=$value;
									$arr['recommend'][1]=0;
								}
							}
						} */
					}
				}
				if($arr['recommend'][0]!=$reg_recommend) {
					$row['status'] = 8;  //推荐码无效
					return json_encode($row,JSON_UNESCAPED_UNICODE);
				}
			}
			//解析IP
			$position = '';
			$login_ip = get_ip();
			$ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$login_ip}");
			if($ip > 0) {
				$ip = json_decode($ip,true);
				if( !empty($ip['data']) ){
					if($ip['data']['region'] && $ip['data']['city']) {
						$position = $ip['data']['region'].' '.$ip['data']['city'];
					} else {
						$position = $ip['data']['country'];
					}
				}
			}
			//注册防骚扰
			$ruzhuc = Db::name('xt_zcfsr')->find();
			if($ruzhuc['open'] == 1) {
				$ntimess = strtotime(date('Y-m-d').' 00:00:00');
				$zcount = Db::name('username')->where("reg_ip='{$login_ip}' AND reg_time>'{$ntimess}' ")->count();
				if($zcount >= $ruzhuc['one_day_count']) {
					$row['status'] = 2;  //对不起您今天注册的会员账号过多
					return json_encode($row,JSON_UNESCAPED_UNICODE);
				}
			}
			//验证是否用户名已注册
			$usercf = Db::name('username')->where('username',$reg_user)->find();
			if($usercf['id'] > 0) {
				$row['status'] = 5;  //会员已经账号存在
				return json_encode($row,JSON_UNESCAPED_UNICODE);
			}
			//是否开启注册送金额
			$t = Db::name('xt_caijin')->where('id',1)->find();
			if($t['open'] == 1) {
				$je = $t['je'];
				$dml = $t['cj_dml'];
			} else {
				$je = 0;
				$dml = 0;
			}
			//将用户信息插入表
			//$reg_pass = md5($reg_pass);
			$ntime = time();
			$login_key = suiji_zifu(15);

			$user_model->setNewUser($arr['id'],$dml,$reg_user,$reg_pass,$arr['username'],$je,$ntime,$login_ip,$position,1,'',0,$from,$login_key);
			$data['mobile']=$phone;
			$data['zcjje'] = $je;
			$data['reg_je'] = $je;
			/* if($arr['recommend'][1]>0){
				$data['dl']=1;
				$data['dl_time'] = time();
				$data['tjm']=$this->code();
				$data['fandian']=$arr['recommend'][1];
			} */
			Db::name('username')->where('username',$reg_user)->update($data);
			Db::name('username')->where('username',$reg_user)->setInc('login_num');
			if($je>0){
				$state = new StateChange();
				$state->UserFaSong($reg_user, "您注册账号赠送：".$je."元.已到账，请注意查收！");
				$data = array(
					'username'=>$reg_user,
					'user_class'=>1,
					'cjje'=>$je,
					'fstime'=>time(),
					'beizhu' => 3==$from ? '系统赠送，Android用户注册，赠送彩金' : '系统赠送，IOS用户注册，赠送彩金',
					'czadmin' => '系统赠送',
					'cjhje'=>$je,
				);
				Db::name('caijin_list')->insert($data);
			}
			$us = Db::name('username')->where('username',$reg_user)->value('id');
	        /*$id = $us;
	    	if(strlen($us)==1){$id='00000'.$us;}
			if(strlen($us)==2){$id='0000'.$us;}
			if(strlen($us)==3){$id='000'.$us;}
			if(strlen($us)==4){$id='00'.$us;}
			if(strlen($us)==5){$id='0'.$us;}
			$dt = array('tjm'=>$id);
			Db::name('username')->where('id',$us)->update($dt);*/
			//标记用户为登录状态
			$row['status'] = 0;  //成功
			$row['datas'] = Db::name('username')->field('id as uid,username,password,login_key,dl,je,0 as bank,swzh as sw')->where('username',$reg_user)->find();
			$row['datas']['sw'] = 0==intval($row['datas']['sw']) ? 1 : 0;
			$row['datas']['image'] = "";
			return json_encode($row,JSON_UNESCAPED_UNICODE);
		} else {
			$row['status'] = 1;  //注册信息不完整
			$row['ResultMsg']='注册信息不完整';
			return json_encode($row,JSON_UNESCAPED_UNICODE);
		}
	}
	function code(){
		$code=rand('00000000','99999999');
		if($code != ''){
			$c = Db::name('username')->where('tjm',$code)->find();
			if($c){
				$this->code();
			}
		}
		return $code;
	}
	public function agreement(){
		return $this->fetch();
	}
	public function shiwan(){
		$swsm = Db::name('xt_shiwan')->find();
		$row = array(
				'result'=>0,
				'ResultMsg'=>'试玩失败',
		);
		$from = input('post.from',3);
		if($swsm['open'] == 1) {
			$username = $swsm['qianzhui'];
			$yuscount = '';
			for($t=1;$t<=$swsm['swcd'];$t++) {
				$yuscount .= rand(0,9);
			}
			$username = $username.$yuscount;
			$password = md5('123456');
			$login_key = suiji_zifu(15);
			//获得IP并解析地址
			$login_ip = get_ip();
			$ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$login_ip}");
			$position = '';
			if( $ip ){
				$ip = json_decode($ip,true);
				if( !empty($ip['data']) ){
					if($ip['data']['region'] && $ip['data']['city']) {
						$position = $ip['data']['region'].' '.$ip['data']['city'];
					} else {
						$position = $ip['data']['country'];
					}
				}
			}
			//写入账号
			$user = new Username();

			$status = $user->setTryPlayUser($username,$password,$swsm['je'],'0','试玩',time(),$login_ip,$position,'1','1',$login_key,'0',$from);
			if( !empty($status) ){
				$data = Db::name('username')->where(['username'=>$username])->find();
				Db::name("username")->where(['username'=>$username])->update(['current_from'=>$from,'current_time'=>time(),'diff_time'=>time()]);
				$row['result'] = 1;
				$row['ResultMsg'] = '试玩成功';
				$row['datas'] = array(
						'uid' => $data['id'],
						'username'=>$username,
						'password'=> $data['password'],
						'login_key'=>$login_key,
						'dl' => intval($data['dl']),
						'je'=>floatval($data['je']),
						'bank' => empty($data['bankno']) ? 0 : 1,
						'sw' => 0,
						'image' => ''
				);
			}
		}
		echo json_encode($row,JSON_UNESCAPED_UNICODE);
	}
	public function updateImg(){

		$data = input('post.');
		$files = $_FILES;
		$base_path = ROOT_PATH.'public'.DS.'uploads'.DS.'avatar'.DS; //存放目录
		if(!is_dir($base_path)){
			mkdir($base_path,0777,true);
		}
		$row = array(
				'result'=>0,
				'ResultMsg'=>'上传失败'
		);

		if(isset($files['file']) && !empty($files['file'])){
			$img = $files['file'];
			$target_path = $base_path.basename( $img['name'] );
			$username = $data['username'];
			$orgImg = Db::name('username')->where(['username'=>$username])->value("img");
			if( move_uploaded_file ( $img['tmp_name'], $target_path ) && Db::name('username')->where(['username'=>$username])->update(['img'=>basename( $img['name'] )]) ){
				if( !empty($orgImg)){
					@unlink($base_path.$orgImg);
				}
				$row['result'] = 1;
				$row['ResultMsg'] = '上传成功';
				$row['datas'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/uploads/avatar/'.basename( $img['name'] );
			}
		}
		echo json_encode($row,JSON_UNESCAPED_UNICODE);
	}
	public function loginout(){
		$user = input('username');
		//Db::name('username')->where('username',$user)->update(['registration_id'=>'']);
		
	}

}

